import { PageModel } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/model/PageModel';
import { ISqliteService } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/service/ISqliteService';
import { SqliteServiceImpl } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/service/impl/SqliteServiceImpl';
import { AppConfig } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/model/AppConfig';
import { Transactional } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/TransactionManager/Transactional';
import { executeSql, selectSql } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/db/SqliteHelper';
import { initDb } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/app/application';
import { DB_NAME } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/config/dbconfig';

export class ApplicationServiceImpl {

	// 创建实现类的实例
	private sqliteService : ISqliteService<AppConfig>;

	constructor() {
		this.sqliteService = new SqliteServiceImpl<AppConfig>();
	}

	// 事务测试
	@Transactional
	transactionalTest(application : AppConfig) : void {
		console.log("处理业务逻辑开始");
		this.sqliteService.insert(application);
		let applications = new AppConfig();
		applications.id = 1;
		applications.name = '这是更改后的名字';
		this.sqliteService.updateById(applications.id, applications);
		this.sqliteService.deleteById(2, AppConfig);
		// 制造一个异常
		this.sqliteService.updateById(applications.id, null!);
		throw new Error("制造一个异常");
	}

	// 插入数据库配置
	async insertApplication(application : AppConfig) : Promise<void> {
		return await this.sqliteService.insert(application);
	}
	
	async saveApp(name : string, dbName : string, secretLevel : string, version : string, url : string) : Promise<Boolean> {
		return initDb(dbName)
			.then(async (dbPath) => {
				const app = await this.getApplicationByDbName(dbName);
				// 已存在则更新
				if (app) {
					await this.updateByDbName(dbName, name, secretLevel, version)
				} else {
					const app = new AppConfig();
					app.code = dbName;
					app.name = name;
					app.dbName = dbName;
					app.dbPath = dbPath;
					app.secretLevel = secretLevel;
					app.version = version;
					app.createdDate = new Date();
					app.url = url;
					this.insertApplication(app)
						.then()
						.catch((err) => {
							console.error("保存失败", err);
							throw err;
						});
				}
				return true;
			})
			.catch((err) => {
				console.error("数据库初始化失败", err);
				return false;
			});
	}

	// 根据 ID 获取数据库配置
	async getApplicationById(id : number) : Promise<AppConfig | null> {
		return await this.sqliteService.selectById(id, AppConfig);
	}
	// 根据 dbName 获取数据库配置
	async getApplicationByDbName(dbName : string) : Promise<AppConfig> {
		const sql = `SELECT * FROM app_config WHERE dbName = '${dbName}'`;
		const result = await selectSql(DB_NAME, sql);
		return result[0];
	}
	
	async updateByDbName(dbName : string, name: string, secretLevel: string,version: string) : Promise<void> {
		const sql = `UPDATE app_config SET name = '${name}' , secretLevel = '${secretLevel}' , version = '${version}' WHERE dbName = '${dbName}'`;
		await executeSql(DB_NAME, sql);
	}
	
	// 根据 ID 获取数据库配置
	async hasApplication(code : string) : Promise<Boolean> {
		const sql = `SELECT * FROM app_config WHERE code = '${code}'`;
		const result = await selectSql(DB_NAME, sql);
		return result[0];
	}


	// 获取所有数据库配置
	async getApplications() : Promise<AppConfig[]> {
		return await this.sqliteService.selectAll(AppConfig);
	}
	
	// 获取所有数据库配置
	async getBusApplications() : Promise<AppConfig[]> {
		return await this.sqliteService.selectByCondition(' code != \'main\'',AppConfig);
	}

	// 根据条件获取用户
	async getApplicationsByCondition(condition : string) : Promise<AppConfig[]> {
		return await this.sqliteService.selectByCondition(condition, AppConfig);
	}

	/**
	 * 分页查询用户
	 */
	async getApplicationsByPage(page : number, size : number, condition ?: string, orderBy ?: string) : Promise<PageModel<AppConfig>> {
		return await this.sqliteService.selectByPage(AppConfig, page, size, condition, orderBy);
	}

	// 更新用户
	async updateApplication(application : AppConfig) : Promise<void> {
		return await this.sqliteService.updateById(application.id, application);
	}

	// 根据 ID 删除数据库配置
	async deleteApplicationById(id : number) : Promise<void> {
		return await this.sqliteService.deleteById(id, AppConfig);
	}

	// 根据条件删除数据库配置
	async deleteApplicationByCondition(condition : string) : Promise<void> {
		return await this.sqliteService.deleteByCondition(condition, AppConfig);
	}
}